package com.gitee.shardingsphere.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gitee.shardingsphere.common.entity.Order;
import com.gitee.shardingsphere.common.entity.OrderItem;
import com.gitee.shardingsphere.dao.mapper.OrderMapper;
import com.gitee.shardingsphere.service.IOrderItemService;
import com.gitee.shardingsphere.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * 开发人员   YooLin1c
 * 编写日期   2018/6/21
 * 联系邮箱   401664157@qq.com
 * 作用描述
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {
    @Autowired
    private IOrderItemService orderItemService;

    @Override
    @Transactional
    public boolean order(Order order) {
        List<OrderItem> itemList = order.getItemList();
        if (this.baseMapper.insert(order) > 0 && !CollectionUtils.isEmpty(itemList)) {
            itemList.forEach(item -> {
                item.setOrderId(order.getOrderId());
                item.setUserId(order.getUserId());
            });
            return orderItemService.saveBatch(itemList);
        }
        return false;
    }

    @Override
    public List<Order> getOrderList() {
        List<Order> orders = this.list(null);
        orders.forEach(order -> {
            List<OrderItem> orderItems = this.orderItemService.list(new QueryWrapper<OrderItem>().lambda()
                    .eq(OrderItem::getOrderId, order.getOrderId())
                    .eq(OrderItem::getUserId, order.getUserId())
            );
            order.setItemList(orderItems);
        });
        return orders;
    }

    @Override
    public boolean cancel(Long orderId) {
        return this.baseMapper.deleteById(orderId) > 0;
    }
}
